// created by noellynch
// Apr 28, 2011

package com.apachepivot.utils;

import java.io.File;

import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.wtk.Alert;
import org.apache.pivot.wtk.FileBrowserSheet;
import org.apache.pivot.wtk.ListView;
import org.apache.pivot.wtk.MessageType;
import org.apache.pivot.wtk.Sheet;
import org.apache.pivot.wtk.SheetCloseListener;
import org.apache.pivot.wtk.Window;

public class FileSheetUtils {
	static	private		String		mstr_curDir;
	static	{
		mstr_curDir = System.getProperty("user.dir");
	}
	
	static	public	String		pwd() {
		return mstr_curDir;
	}
	
	static	public	void	setPWD(File cl_f) {
		if(cl_f.isDirectory()) {
			mstr_curDir = cl_f.getPath();
		} else {
			mstr_curDir = cl_f.getParent();
		}
	}
	
	static	public	void		getAFile(Window cl_owner, boolean b_open, boolean b_dir, final IHandleFileSelection cl_sel) {
		FileBrowserSheet.Mode		lcl_sheetMode = null;
		
		if(b_dir) {
			lcl_sheetMode = FileBrowserSheet.Mode.SAVE_TO;
		} else {
			if(b_open) {
				lcl_sheetMode = FileBrowserSheet.Mode.OPEN;
			} else {
				lcl_sheetMode = FileBrowserSheet.Mode.SAVE_AS;
			}
		}
		
		final FileBrowserSheet fileBrowserSheet = new FileBrowserSheet();
		fileBrowserSheet.setRootDirectory(new File(pwd())); 
		
        if (lcl_sheetMode == FileBrowserSheet.Mode.SAVE_AS) {
            fileBrowserSheet.setSelectedFile(new File(fileBrowserSheet.getRootDirectory(), "New File"));
        }

        fileBrowserSheet.setMode(lcl_sheetMode);
        fileBrowserSheet.open(cl_owner, new SheetCloseListener() {
            @Override
            public void sheetClosed(Sheet sheet) {
                if (sheet.getResult()) {
                    Sequence<File> selectedFiles = fileBrowserSheet.getSelectedFiles();
                    File		lcl_sel = selectedFiles.get(0);
                    setPWD(lcl_sel);
                    
                    if(cl_sel != null) {
                    	cl_sel.fileSelected(lcl_sel);
                    }
                }
            }
        });
	}
	
	public	interface	IHandleFileSelection {
		void	fileSelected(File cl_f);
	}
}
